from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

from common.token import parse_payload
from user.models import User
from common.http import render_json


class AuthMiddleware(MiddlewareMixin):
    White_list = [
        '/user/login',
        '/favicon.ico',
    ]

    def process_request(self, request):
        # for path in self.White_list:
        if request.path in self.White_list:
            return
        # 进行token验证
        authorization = request.META.get('HTTP_AUTHORIZATION', '')
        auth = authorization.split()
        if not auth:
            # from django.core.exceptions import BadRequest
            # raise BadRequest('Invalid request.')
            return render_json("Can't request, please add token.", code=11)
        if auth[0] != 'Bearer':
            return render_json('authorization 请求头中认证方式错误', code=11)
        if len(auth) == 1:
            return render_json('非法authorization请求头', code=11)
        elif len(auth) > 2:
            return render_json('非法authorization请求头', code=11)

        token = auth[1]
        result = parse_payload(token)
        if result.get('error'):
            return render_json(result.get('error'), code=11)
        uid = result.get('data')['uid']
        if uid:
            try:
                request.user = User.objects.get(id=uid)
                return
            except:
                return render_json('用户不存在', code=11)
        else:
            return render_json('token验证失败,请重新登录', code=11)


class CorsMiddleware(MiddlewareMixin):  # 跨域中间件
    def process_request(self, request):
        if request.method == 'OPTIONS' and 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
            response = HttpResponse()
            response['Content-Length'] = '0'
            response['Access-Control-Allow-Headers'] = request.META
            response['Access-Control-Allow-Origin'] = '*'
            return response

    def process_response(self, request, response):
        # response["Content-Type"] = "application/json"  # 响应信息的内容格式
        response["Access-Control-Allow-Origin"] = "*"  # 允许跨域请求的源地址， * 表示：允许所有地址
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PATCH"  # 允许跨域请求的具体方法
        response["Access-Control-Max-Age"] = "1000"  # 用来指定本次预检请求的有效期，单位为秒，，在此期间不用发出另一条预检请求。
        response["Access-Control-Allow-Headers"] = "*"
        return response
